package com.yan.utils;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class DBUtil {
    /**
     * 配置数据库
     */
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        Properties properties = new Properties();
        InputStream resource = DBUtil.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            properties.load(resource);
        }catch (Exception e){
            e.printStackTrace();
        }
        driver = properties.getProperty("driver");
        url = properties.getProperty("url");
        username = properties.getProperty("username");
        password = properties.getProperty("password");
    }
    /**
     * 数据库连接
     */
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        }catch (Exception e){
            e.printStackTrace();
        }
        return connection;
    }
    /**
     * 释放资源
     *
     */
    public static boolean closeResource(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet){
        boolean flag = true;
        if(resultSet != null){
            try{
                resultSet.close();
                resultSet = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        if(preparedStatement != null){
            try {
                preparedStatement.close();
                preparedStatement = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        if(connection != null){
            try {
                connection.close();
                connection = null;
            }catch (SQLException e){
                e.printStackTrace();
                flag = false;
            }
        }
        return flag;
    }
}
